package bolao.persistence;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Scanner;

import bolao.entities.Aposta;

public class ApostaDAO {

	
	public Aposta recuperarAposta(int id) throws IOException, ClassNotFoundException {

		
		FileInputStream fis = new FileInputStream("apostas/aposta#" + id + ".ap");
		ObjectInputStream in = new ObjectInputStream(fis);
		return (Aposta) in.readObject();	
	}

	
	public void salvarAposta(Aposta aposta) throws IOException {
		
		if(aposta.getId() == 0){
			aposta.setId(getNextId());
		}
		
		FileOutputStream fos = new FileOutputStream("apostas/aposta#" + aposta.getId() + ".ap");
		ObjectOutputStream out = new ObjectOutputStream(fos);
		out.writeObject(aposta);
		out.close();		
	}

	private int getNextId() throws IOException {
		FileInputStream fis = new FileInputStream("controle/aposta_Id");
		Scanner scan = new Scanner(fis);
		Integer id = scan.nextInt();
		id++;
		FileOutputStream fos = new FileOutputStream("controle/aposta_Id");
		fos.write(id.toString().getBytes());
		return id;
	}

}
